package com.chap4;

import com.chap1.tools.SleepTools;

import java.util.Random;

import static javafx.scene.input.KeyCode.T;

/**
 * <p>
 * <code>ThreadLocalUnSafe</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-28 9:08
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class ThreadLocalUnSafe implements Runnable {

    public static ThreadLocal<Number> value = new ThreadLocal<Number>(){
        @Override
        protected Number initialValue() {
            return new Number(0);
        }
    };

    @Override
    public void run(){
        Random random = new Random();
        Number number = value.get();
        number.setNum(number.getNum()+random.nextInt(100));
        value.set(number);
        SleepTools.ms(2);
        System.out.println(Thread.currentThread().getName()+"="+value.get().getNum());
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new ThreadLocalUnSafe()).start();

        }
    }

    private static class Number{
        private int num;

        public Number(int num) {
            this.num = num;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        @Override
        public String toString() {
            return "Number{" +
                    "num=" + num +
                    '}';
        }
    }

}
